package com.etlmaster.executor.steps.table;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("checkExistsTable")
public class CheckTableStep extends Step {
	
	private CheckTableStepMeta meta;
	
	public CheckTableStep(StepMeta meta) {
		super(meta);
		this.meta=(CheckTableStepMeta)meta;
		// TODO Auto-generated constructor stub
	}

	@Override
	protected int handle() {
		String realTableName="";
		DataSourceDefine def=DataSourceHolder.getInstance().getDataSourceDefine(meta.getDsName());
		try{
			JdbcTemplate jdbcTemplate = new JdbcTemplate(meta.getDsName());
			
			String dsType = DataCollectionUtils.getDsType(meta.getDsName());
			StringBuilder sql=new StringBuilder();
			realTableName=meta.variableSubstitution(meta.getTableName());
			int row = 0;
			//hive需要调用excute方法
			if(dsType.equals("hive")){
				sql.append("desc ").append(realTableName);
				meta.log("INFO","查看表是否存在{}",sql.toString());
				jdbcTemplate.execute(sql.toString());
			}else{
				sql.append("select 1 from  ")
				   .append(realTableName)
				   .append(" where 1=2");
				jdbcTemplate.execute(sql.toString());
			}
			meta.log("INFO","表:{}已经存在数据库{} 中用户{}",realTableName,meta.getDsName(),def.getUsername());
			return StepState.RUNNING_SUCCESSED;
		}catch(Exception e){
			meta.log("ERROR","表:{}不存在数据库{} 中用户{}",realTableName,meta.getDsName(),def.getUsername());
			return StepState.RUNNING_FAILED;
		}
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	

}
